//
//  SettingsViewController.m
//  jingdongfang
//
//  Created by 郝志宇 on 16/6/24.
//  Copyright © 2016年 XuDong Jin. All rights reserved.
//

#import "SettingsViewController.h"
#import "LoginViewController.h"
#import "AppDelegate.h"
#import "ChangePasswordViewController.h"
#import "PhoneNumViewController.h"
#import "FeedBackViewController.h"
#import <AFNetworking.h>
#import "IGWebViewController.h"

IGUserInfo *userInfoModel;
@interface SettingsViewController () <UITableViewDelegate, UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *table;
@property (nonatomic, copy) NSString *appInStoreVersion;

@end

@implementation SettingsViewController
#pragma mark -生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
//    self.title = @"设置";
    self.title = NSLocalizedString(@"Setting", nil);
    _appInStoreVersion = @"0";
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, 100)];
    UIButton *logOut = [UIButton buttonWithType:UIButtonTypeCustom];
    logOut.layer.cornerRadius = 20.f;
    logOut.layer.masksToBounds = YES;
    logOut.backgroundColor =RGB(240, 125, 125);
    logOut.frame = CGRectMake(0, 0, GSCALE(300), GSCALE(44));
    logOut.titleLabel.font = [UIFont systemFontOfSize:20];
    [logOut setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    [logOut setTitle:@"退出登录" forState:UIControlStateNormal];
    [logOut setTitle:NSLocalizedString(@"Log Out", nil) forState:UIControlStateNormal];
    [logOut addTarget:self action:@selector(logOutAction:) forControlEvents:UIControlEventTouchUpInside];
    logOut.center = CGPointMake(view.width/2, view.height/2);
    [view addSubview:logOut];
    self.table.tableFooterView = view;
    [self appStoreVersion];
}

- (void)appStoreVersion {
    AFHTTPSessionManager *manager  = [AFHTTPSessionManager manager];
    NSString *urlStr = [NSString stringWithFormat:@"http://itunes.apple.com/cn/lookup?id=%@", STOREAPPID];
    [manager GET:urlStr parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSArray *array = responseObject[@"results"];
        NSDictionary *dic = array[0];
        self.appInStoreVersion = dic[@"version"];
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:1 inSection:1];
        [self.table reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        _appInStoreVersion = @"0";
    }];
}

#pragma mark - UITableViewDelegate, UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 2;
    }
    return 5;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:nil];
    cell.textLabel.font = [UIFont font16];
    cell.detailTextLabel.font = [UIFont font16];
    if (indexPath.section==0) {
        if (indexPath.row==0) {
//            cell.textLabel.text = @"手机绑定";
            cell.textLabel.text = NSLocalizedString(@"Link your mobile", nil);
            if (![IGUser getTel].length) {
//                cell.detailTextLabel.text = @"未绑定";
                cell.detailTextLabel.text = NSLocalizedString(@"Unlinked", nil);
                cell.userInteractionEnabled=YES;
            } else {
                cell.detailTextLabel.text = [IGUser getTel];
                cell.userInteractionEnabled=NO;
            }
        } else if (indexPath.row==1) {
//            cell.textLabel.text = @"密码修改";
            cell.textLabel.text = NSLocalizedString(@"Change Password", nil);
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
    } else if (indexPath.section==1) {
        if (indexPath.row==0) {
//            cell.textLabel.text = @"清除缓存";
            cell.textLabel.text = NSLocalizedString(@"Clean Cache", nil);
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        } else if (indexPath.row==1) {
//            cell.textLabel.text = @"软件版本";
            cell.textLabel.text = NSLocalizedString(@"Software Version", nil);
            cell.detailTextLabel.font = [UIFont font12];
            //获得当前版本号
            NSDictionary *infoDic=[[NSBundle mainBundle] infoDictionary];
            NSString *currentVersion=infoDic[@"CFBundleShortVersionString"];
            if ([currentVersion floatValue] >= [_appInStoreVersion floatValue]) {
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.detailTextLabel.text = currentVersion;
            } else if([currentVersion floatValue] < [_appInStoreVersion floatValue]){
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                cell.detailTextLabel.text = [NSString stringWithFormat:@"已有新版本[%@],点击更新", _appInStoreVersion];
            }
        }else if (indexPath.row==2){
//            cell.textLabel.text = @"关于我们";
            cell.textLabel.text = NSLocalizedString(@"About Us", nil);
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }else if (indexPath.row==3){
//            cell.textLabel.text = @"用户协议";
            cell.textLabel.text = NSLocalizedString(@"User Agreement", nil);
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }else if (indexPath.row==4){
//            cell.textLabel.text = @"意见反馈";
            cell.textLabel.text = NSLocalizedString(@"Feedback", nil);
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        
    } return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0 ) {
        if (indexPath.row == 0) {//手机绑定
            PhoneNumViewController *phoneVC = [[UIStoryboard storyboardWithName:@"Setting" bundle:nil] instantiateViewControllerWithIdentifier:@"PhoneNumViewController"];
            [UIViewController ig_pushViewController:phoneVC animated:YES];
        } else if (indexPath.row == 1) {//修改密码
            if ([IGUser getTel].length != 0) {
                ChangePasswordViewController *changePassVC = [[UIStoryboard storyboardWithName:@"Setting" bundle:nil] instantiateViewControllerWithIdentifier:@"ChangePasswordViewController"];
                [UIViewController ig_pushViewController:changePassVC animated:YES];
            } else {
                PhoneNumViewController *phoneVC = [[UIStoryboard storyboardWithName:@"Setting" bundle:nil] instantiateViewControllerWithIdentifier:@"PhoneNumViewController"];
                [UIViewController ig_pushViewController:phoneVC animated:YES];
            }
        }
    } else if (indexPath.section==1) {
        //清除缓存
        if (indexPath.row == 0) {
//            @"提示\n是否清除本地缓存数据?"
            NSString *notice = [NSString stringWithFormat:@"%@\n%@",NSLocalizedString(@"Notice", nil),NSLocalizedString(@"Clean Cache?", nil)];
            [UIAlertView bk_showAlertViewWithTitle:@"" message:notice cancelButtonTitle:NSLocalizedString(@"Cancel", nil) otherButtonTitles:@[NSLocalizedString(@"Confirm", nil)] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
                if (buttonIndex == 1) {
                    NSString *cachePath = [NSSearchPathForDirectoriesInDomains (NSCachesDirectory , NSUserDomainMask, YES) firstObject];
                    [self cleanCaches:cachePath];
                }
            }];
        } else if (indexPath.row==1) {//软件升级
            NSDictionary *infoDic=[[NSBundle mainBundle] infoDictionary];
            NSString *currentVersion=infoDic[@"CFBundleShortVersionString"];
            if ([currentVersion floatValue] >= [_appInStoreVersion floatValue]) {
                return;
            }
            //当前版本号小于商店版本号,就更新
            if([currentVersion floatValue] < [_appInStoreVersion floatValue]) {
//                New version X available. Update now?
                [UIAlertView bk_showAlertViewWithTitle:NSLocalizedString(@"New Version Available", nil) message:[NSString stringWithFormat:@"%@(%@)%@?", NSLocalizedString(@"New version available", nil),_appInStoreVersion,NSLocalizedString(@"Update now?", nil)] cancelButtonTitle:NSLocalizedString(@"Cancel", nil) otherButtonTitles:@[NSLocalizedString(@"Update", nil)] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
                    if (buttonIndex == 1) {
                        NSURL *url = [NSURL URLWithString:@"https://itunes.apple.com/cn/app/%E7%94%BB%E5%B1%8F/id1150322560?mt=8"];
                        [[UIApplication sharedApplication] openURL:url];
                    }
                }];
            }
        } else if(indexPath.row==2){//关于我们
            IGWebViewController *vc = [[IGWebViewController alloc] initWithType:IGWebViewTypeEigth];
            [UIViewController ig_pushViewController:vc animated:YES];
        } else if(indexPath.row==3){//用户协议
            IGWebViewController *vc = [[IGWebViewController alloc] initWithType:IGWebViewTypeThree];
            [UIViewController ig_pushViewController:vc animated:YES];
        } else if(indexPath.row==4){//意见反馈
            FeedBackViewController *feedBackVC = [[UIStoryboard storyboardWithName:@"Setting" bundle:nil] instantiateViewControllerWithIdentifier:@"FeedBackViewController"];
            [UIViewController ig_pushViewController:feedBackVC animated:YES];
        }
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section==0) {
        return 10.f;
    }
    return 10.f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return .01f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}
#pragma mark -退出登录
- (void)logOutAction:(UIButton *)btn {
    [UIAlertView bk_showAlertViewWithTitle:@"" message:NSLocalizedString(@"Confirm to Log Out?", nil) cancelButtonTitle:NSLocalizedString(@"Cancel", nil) otherButtonTitles:@[NSLocalizedString(@"Confirm", nil)] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex == 1) {
//            NSString *tags = [[NSString alloc]init];
//            NSSet *tagSet = [NSSet setWithObject:tags];
            
            [JPUSHService setAlias:@"zhuxiaojiguangbieming" completion:nil seq:1];
            [JPUSHService setTags:nil completion:nil seq:1];
            [kAPPDELEGATE configLoginVC];
        }
    }];
}
#pragma mark -清除缓存
- (void)cleanCaches:(NSString *)path{
    // 利用NSFileManager实现对文件的管理
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:path]) {
        // 获取该路径下面的文件名
        NSArray *childrenFiles = [fileManager subpathsAtPath:path];
        for (NSString *fileName in childrenFiles) {
            // 拼接路径
            NSString *absolutePath = [path stringByAppendingPathComponent:fileName];
            // 将文件删除
            [fileManager removeItemAtPath:absolutePath error:nil];
        }
    }
//    [self presentMessageTips:@"清除完成"];
    [self presentMessageTips:NSLocalizedString(@"Cache Cleaned !", nil)];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
